# apps/app01/views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from apps.app01.models import Product
from apps.app01.views.search.serializer.product_list import ProductListSerializer
from django.db.models import Q

class SearchView(APIView):
    authentication_classes = []
    def post(self, request, format=None):
        data = request.data
        # 提取请求参数
        limit = data.get('limit')
        current_page = data.get('currentPage')
        brand = data.get('brand', '').strip()
        series = data.get('series', '').strip()
        color = data.get('color', '').strip()
        memory = data.get('memory')
        storage = data.get('storage')
        order_by = data.get('orderBy', 'recommend')
        in_stock = data.get('inStock')
        keyword = data.get('keyword', '').strip()
        start_price = data.get('startPrice')
        end_price = data.get('endPrice')

        # 验证必填参数
        if limit is None or current_page is None:
            return Response({
                'code': 400,
                'message': '参数缺失：limit 和 currentPage 是必填项。'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            limit = int(limit)
            current_page = int(current_page)
        except ValueError:
            return Response({
                'code': 400,
                'message': '参数错误：limit 和 currentPage 必须为整数。'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 构建查询集
        queryset = Product.objects.all()

        if brand:
            queryset = queryset.filter(name__icontains=brand)

        if series:
            queryset = queryset.filter(brief__icontains=series)

        if color:
            queryset = queryset.filter(color__icontains=color)

        if memory is not None:
            try:
                memory = int(memory)
                queryset = queryset.filter(memory=memory)
            except ValueError:
                return Response({
                    'code': 400,
                    'message': '参数错误：memory 必须为整数。'
                }, status=status.HTTP_400_BAD_REQUEST)

        if storage is not None:
            try:
                storage = int(storage)
                queryset = queryset.filter(storage=storage)
            except ValueError:
                return Response({
                    'code': 400,
                    'message': '参数错误：storage 必须为整数。'
                }, status=status.HTTP_400_BAD_REQUEST)

        if keyword:
            queryset = queryset.filter(Q(name__icontains=keyword) | Q(brief__icontains=keyword))

        if start_price is not None:
            try:
                start_price = float(start_price)
                queryset = queryset.filter(price__gte=start_price)
            except ValueError:
                return Response({
                    'code': 400,
                    'message': '参数错误：startPrice 必须为数字。'
                }, status=status.HTTP_400_BAD_REQUEST)

        if end_price is not None:
            try:
                end_price = float(end_price)
                queryset = queryset.filter(price__lte=end_price)
            except ValueError:
                return Response({
                    'code': 400,
                    'message': '参数错误：endPrice 必须为数字。'
                }, status=status.HTTP_400_BAD_REQUEST)

        # 排序
        if order_by == 'price':
            queryset = queryset.order_by('price')
        elif order_by == '-price':
            queryset = queryset.order_by('-price')
        elif order_by == 'new':
            queryset = queryset.order_by('-id')  # 假设 id 代表新商品
        elif order_by == 'review':
            queryset = queryset.order_by('-id')  # 示例，无实际评分字段
        # sorter == 0 或其他值时，无需排序

        # 计算总数和总页数
        total_items = queryset.count()
        page_sum = (total_items + limit - 1) // limit  # 向上取整

        # 分页
        offset = (current_page - 1) * limit
        queryset = queryset[offset:offset + limit]

        # 序列化数据
        serializer = ProductListSerializer(queryset, many=True)
        products = serializer.data

        return Response({
            'code': 200,
            'message': '成功',
            'data': {
                'pageSum': page_sum,
                'totalItems': total_items,
                'products': products
            }
        }, status=status.HTTP_200_OK)
